<template>
  <div>
    <!-- 活动信息展示 -->
    <HeaderInfo
      :info="activityInfo"
      @refresh="refreshActivityDetail"
      @openOfficialAccountModal="openOfficialAccountModal"
      @openQrcodeModal="openQrcodeModal"
      @openCancelActivityModal="handleConfirmCancelActivity"
      @toggleDisplay="toggleDisplay"
      @sendMessage="sendMessage"
      @openDeleteModal="openDeleteModal"
      @openOrganizationLabel="openOrganizationLabel"
    />

    <!-- 活动数据区域 -->

    <div v-if="activityInfo.maxPrice > 0" class="disFlxJS gap-20">
      <StatisticsHost
        :info="activityCount"
        :isExistJointly="isExistJointly"
        @setUntrueNum="setUntrueNum"
        @refresh="refreshCount"
      />
      <Statisticsticket :info="activityTicketCount" :isExistJointly="isExistJointly" />
    </div>
    <Statistics
      v-else
      :info="activityCount"
      :isExistJointly="isExistJointly"
      @setUntrueNum="setUntrueNum"
      @refresh="refreshCount"
    />

    <!-- 表格区域 -->
    <a-card
      :tab-list="tabList"
      :active-tab-key="titleKey"
      @tabChange="key => onTabChange(key)"
      :bordered="false"
      class="_mt-20"
      :bodyStyle="{ padding: '0' }"
    >
      <div v-if="titleKey === 'registrationList'">
        <RegistrationList key="registrationList" :ref="titleKey" :titleKey="titleKey" @refresh="refreshCount" />
      </div>
      <div v-else-if="titleKey === 'registrationListApproved'">
        <RegistrationList
          :ref="titleKey"
          key="registrationListApproved"
          :titleKey="titleKey"
          @refresh="refreshCount"
          :approvalStatus="RosterApprovalStatusEnum.APPROVED"
        />
      </div>
      <div v-else-if="titleKey === 'approvalList'">
        <ApprovalList :ref="titleKey" :titleKey="titleKey" :approvalStatus="1" @refresh="refreshCount" />
      </div>
      <div v-else-if="titleKey === 'signList'">
        <SignList :ref="titleKey" :titleKey="titleKey" :signStatus="signStatusEnum.END" @refresh="refreshCount" />
      </div>
      <div v-else-if="titleKey === 'ticketRefundRecords'">
        <TicketRefundRecords
          key="ticketRefundRecords"
          :ref="titleKey"
          :titleKey="titleKey"
          @refresh="refreshCount"
          :approvalStatus="RosterApprovalStatusEnum.CANCELLED"
        />
      </div>
      <div v-else-if="titleKey === 'browsingHistory'">
        <BrowsingHistory :ref="titleKey" :activityId="activityInfo.id" />
      </div>
    </a-card>

    <!-- 插入公众号 -->
    <InsetOfficialAccountModal ref="insetOfficialAccountModal" />

    <!-- 分享活动 -->
    <ShareModal ref="ShareModal" />

    <SuccessModal ref="successModal" title="取消成功" :close="backList" :confirm="sendCloseMessage" confirmText="" />

    <!-- 举办单位标签设置 -->
    <OrganizationLabel ref="OrganizationLabel" :activityId="activityInfo.id" />
    <DashboardGuide />
  </div>
</template>

<script>
import HeaderInfo from './headerInfo.vue'
import Statistics from './statistics.vue'
import StatisticsHost from './statisticsHost.vue'
import Statisticsticket from './statisticsticket.vue'
import {
  getActivityInfo,
  getActivityCountInfo,
  activityDisplay,
  editSection,
  activityDel,
  setUntrueNum,
  getActivityTicketCountInfo
} from '@/api/activity/activity'
import { getLink } from '@/utils/common'
import InsetOfficialAccountModal from '@/components/InsetOfficialAccountModal'
import ShareModal from '@/components/ShareModal/index.vue'
import SuccessModal from '@/components/SuccessModal'
import BrowsingHistory from '@/views/activity/components/browsingHistory'
import RegistrationList from '../registrationList'
import TicketRefundRecords from '../ticketRefundRecords'
import ApprovalList from '../registrationList'
import SignList from '../registrationList'
import OrganizationLabel from '@/views/activity/components/organizationLabel/index.vue'

import { signStatusEnum, activityStatusEnum, displayEnum, RosterApprovalStatusEnum } from '@/enums/activity'
import { cancelActivityErr } from '@/utils/codes'
import DashboardGuide from '../components/DashboardGuide/index.vue'
export default {
  components: {
    HeaderInfo,
    Statistics,
    StatisticsHost,
    Statisticsticket,
    InsetOfficialAccountModal,
    ShareModal,
    SuccessModal,
    BrowsingHistory,
    RegistrationList,
    ApprovalList,
    SignList,
    OrganizationLabel,
    TicketRefundRecords,
    DashboardGuide
  },
  data() {
    return {
      RosterApprovalStatusEnum,
      activityInfo: {},
      activityCount: {},
      activityTicketCount: {},
      cancelActivityModalShow: false,
      titleKey: 'registrationList',
      signStatusEnum,
      isExistJointly: false // 判断主办方是否存在协办
    }
  },
  computed: {
    tabList() {
      return [
        {
          key: 'registrationList',
          tab: '全部报名名单'
        },
        {
          key: 'registrationListApproved',
          tab: `报名成功（${
            this.activityInfo.activityType === 'oneself'
              ? this.activityCount.passedNum
              : this.activityCount.passedNumByCurrentTenant
          }）`
        },

        {
          key: 'signList',
          tab: `已签到名单（${
            this.activityInfo.activityType === 'oneself'
              ? this.activityCount.registerSignNum
              : this.activityCount.registerSignNumByCurrentTenant
          }）`
        },
        {
          key: 'approvalList',
          tab: `报名待审核（${
            this.activityInfo.activityType === 'oneself'
              ? this.activityCount.waitingReviewNum
              : this.activityCount.waitingReviewNumByCurrentTenant
          }）`
        },
        {
          key: 'ticketRefundRecords',
          tab: `取消报名申请（${
            this.activityInfo.activityType === 'oneself'
              ? this.activityCount.cancelRegisterNum
              : this.activityCount.cancelRegisterNumByCurrentTenant
          }）`
        },
        {
          key: 'browsingHistory',
          tab: '本会浏览记录'
        }
      ]
    }
  },
  created() {
    this.getActivityDetails()
    this.getActivityCount()
    this.queryActivityTicketCountInfo()
  },
  methods: {
    refreshCount() {
      this.getActivityCount()
      this.queryActivityTicketCountInfo()
    },
    // 获取活动详情
    async getActivityDetails() {
      const { activityId } = this.$route.query
      const { data } = await getActivityInfo(activityId)
      this.activityInfo = data
      this.isExistJointly = data.activityCooperateOrgList && data.activityCooperateOrgList.length > 1
    },
    // 获取活动统计
    async getActivityCount() {
      const { activityId } = this.$route.query
      const { data } = await getActivityCountInfo(activityId)
      this.activityCount = data
    },
    // 获取活动报名统计
    async queryActivityTicketCountInfo() {
      const { activityId } = this.$route.query
      const { data } = await getActivityTicketCountInfo(activityId)
      this.activityTicketCount = data
    },
    // 刷新整个活动详情
    refreshActivityDetail() {
      this.getActivityDetails()
      this.refreshCount()
      this.$refs[this.titleKey].handleReset()
    },

    // 插入公众号
    openOfficialAccountModal() {
      let link = getLink('activityDetails', { id: this.activityInfo.id })
      this.$refs.insetOfficialAccountModal.openModel(link)
    },
    // 分享活动
    openQrcodeModal() {
      this.$refs.ShareModal.openModel(this.activityInfo.id, this.activityInfo.title)
    },
    async cancelActivity() {
      const res = await editSection({
        id: this.activityInfo.id,
        activityStatus: activityStatusEnum.CANCEL,
        display: displayEnum.HIDE
      })
      if (res.code === 0) {
        this.getActivityDetails()
        this.$refs.successModal.showModal()
      }
      if (res.code === cancelActivityErr) {
        this.$warning({
          title: '取消活动失败',
          width: 500,
          content: () => {
            const h = this.$createElement
            return h('div', [
              h('p', '请完成下面的所有事情后，再取消活动：'),
              h(
                'div',
                {
                  style: {
                    padding: '9px 16px',
                    background: '#E8FFEA'
                  }
                },
                [
                  JSON.parse(res.msg).map((item, index) => {
                    return h('p', `${index + 1}.${item}`)
                  })
                ]
              )
            ])
          },
          onOk: () => {
            this.$destroyAll()
          }
        })
      }
    },
    // 取消活动
    async handleConfirmCancelActivity() {
      this.$confirm({
        icon: 'info-circle',
        title: `取消活动`,
        content: '确定要取消活动',
        okText: `取消活动`,
        cancelText: '暂不取消',
        okButtonProps: {
          props: {
            type: 'danger'
          }
        },
        onOk: async () => {
          await this.cancelActivity()
          this.refreshActivityDetail()
        }
      })
    },

    // 发送取消活动通知
    sendCloseMessage() {
      this.$store.commit('SET_SMSTEMPLATEOBJ', {
        ids: [1, 13],
        data: [
          {
            name: '取消活动通知',
            associatedObjects: 'activity',
            customType: 0,
            dataSource: 'registerList',
            parentId: 1,
            nodeList: null,
            id: 13
          }
        ]
      })
      this.$store.commit('SET_PAGESELECTEDOBJ', {})
      this.$router.push({
        path: '/operations/createMessage',
        query: {
          objectId: this.activityInfo.id
        }
      })
    },

    // 切换展示类型
    async toggleDisplay() {
      let params = {
        id: this.activityInfo.id,
        display: this.activityInfo.display ? displayEnum.SHOW : displayEnum.HIDE
      }
      await activityDisplay(params)
      this.activityInfo.display = params.display
      this.$message.success('修改展示状态成功')
    },
    // 发消息邀约
    sendMessage() {
      this.$store.commit('SET_SMSTEMPLATEOBJ', {
        ids: [1, 6],
        data: [
          {
            name: '邀请参会通知',
            associatedObjects: 'activity',
            customType: 0,
            dataSource: 'userList',
            parentId: 1,
            nodeList: null,
            id: 6
          }
        ]
      })
      this.$store.commit('SET_PAGESELECTEDOBJ', {})
      this.$router.push({
        path: '/operations/createMessage',
        query: { objectId: this.activityInfo.id }
      })
    },
    // 删除
    openDeleteModal() {
      const delFn = async () => {
        const res = await activityDel([this.activityInfo.id])
        if (res.code) return Promise.reject()
        this.$message.success(`删除成功`)
        this.backList()
      }

      const delFall = async () => {
        if (this.activityInfo.activityStatus !== activityStatusEnum.CANCEL) {
          this.$confirm({
            icon: 'info-circle',
            title: `删除失败`,
            content: '活动未在取消状态，不可删除活动。是否要去取消活动？',
            okText: `取消活动`,
            cancelText: '关闭',
            okButtonProps: {
              props: {
                type: 'danger'
              }
            },
            onOk: async () => {
              await this.cancelActivity()
            }
          })
        } else {
          await delFn()
        }
      }
      this.$confirm({
        icon: 'info-circle',
        title: `删除活动`,
        content:
          '确认要删除活动？删除活动将把本活动信息删除，不影响报名订单记录，可在【订单】-【业务订单】-【活动报名订单】内搜索本活动名称查看订单记录。',
        okButtonProps: {
          props: {
            type: 'danger'
          }
        },
        okText: `删除活动`,
        cancelText: '暂不删除',
        onOk: async () => {
          await delFall()
        }
      })
    },

    //返回列表
    backList() {
      this.$router.replace({ path: '/activity/activityList' })
    },

    onTabChange(key) {
      this.titleKey = key
    },

    setUntrueNum(val) {
      setUntrueNum({
        activityId: this.activityInfo.id,
        untruePassedNum: val
      }).then(() => {
        this.$message.success('设置成功')
        this.refreshCount()
      })
    },

    // 打开举办单位设置弹窗
    openOrganizationLabel() {
      this.$refs.OrganizationLabel.openModel()
    }
  }
}
</script>

<style lang="less" scoped></style>
